<template>
  <el-button type="primary" @click="add('add')" style="margin-bottom: 10px;">新增</el-button>
  <el-table :data="data.tableData" row-key="id" table-layout="auto" style="width: 100%">
    <el-table-column prop="value" label="关键词" width="" />
    <el-table-column prop="" label="操作" width="" fixed="right">
      <template #default="scope">
        <el-button type="primary" @click="add('edit', scope.row)">编辑</el-button>
        <el-button type="danger" @click="deleteColumn(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="getList" @current-change="getList" style="margin-top: 20px;display:flex;justify-content: flex-end;" />
  <dialogForm ref="dialogFormRef" @resetList="getList"></dialogForm>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { keywordConfigApi } from '@/api/allApi'
import dialogForm from './dialogForm.vue'
import { ElMessage, ElMessageBox } from 'element-plus/es'

const pageNum = ref(1) // 第几页
const pageSize = ref(10) // 每页多少条
const total = ref(0) // 总条数
const data = reactive({
  tableData: []
})

onMounted(() => {
  getList()
})

const getList = () => {
  keywordConfigApi.getAll({websiteId: Number(localStorage.getItem('WebsiteId'))}).then((res: any) => {
    if (res.code === 0) {
      data.tableData = res.data
      total.value = res.data.length // 假设返回数据是一个数组
    } else {
      ElMessage.success(res.msg)
    }
  })
}

const dialogFormRef = ref()
const add = (type: string, row: any) => {
  dialogFormRef.value.init(type, row)
}

const deleteColumn = (row: any) => {
  ElMessageBox.confirm(`确定删除这个关键词配置吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    keywordConfigApi.delete(row.id).then((res: any) => {
      if (res.code === 0) {
        ElMessage.success('删除成功')
        getList()
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}
</script>

<style lang="scss" scoped>
// 搭配el-table里的table-layout="auto"属性，再让每一列里的width为空即可展现出适应表格内容的列宽
:deep(.el-table .cell) {
  width: max-content;
  display: inline-block;
}
</style>
